package com.zidongxiangxi.rabbit.producer.support;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * RabbitMQ消息加工类
 *
 * @author chenxudong
 * @date 2020/11/07
 */
public class RabbitMessagePostProcessor implements MessagePostProcessor {
	private final String application;

	public RabbitMessagePostProcessor(String application) {
		this.application = application;
	}

	@Override
	public Message postProcessMessage(Message message) throws AmqpException {
		MessageProperties messageProperties = message.getMessageProperties();
		String messageId = messageProperties.getMessageId();
		// 消息id
		if (StringUtils.isEmpty(messageId)) {
			messageProperties.setMessageId(UUID.randomUUID().toString());
		}
		// 发送消息的应用
		String produceApplication = messageProperties.getAppId();
		if (StringUtils.isEmpty(produceApplication)) {
			messageProperties.setAppId(application);
		}
		// 持久化
		MessageDeliveryMode deliveryMode = messageProperties.getDeliveryMode();
		if (!Objects.equals(deliveryMode, MessageDeliveryMode.PERSISTENT)) {
			messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
		}
		// 时间戳
		Date timestamp = message.getMessageProperties().getTimestamp();
		if (Objects.isNull(timestamp)) {
			message.getMessageProperties().setTimestamp(new Date());
		}
		return message;
	}
}

